import { resInfo } from '../utils/common.js'
import Vue from 'vue'
let API_URL = ''
//开发环境与生产环境
if (process.env.NODE_ENV === 'development') {
	//开发环境API 和 路由
	// API_URL = 'https://pd.lotaoup.com/api'
	
	API_URL = 'https://localhost:8080/api'
	// Vue.prototype.$BASE_PATH = 'https://pdm.lotaoup.com'
	
	Vue.prototype.$BASE_PATH = 'https://localhost:8080/api'

    // Vue.prototype.$BASE_PATH = 'https://pdm.lotaoup.com'



}else{
	//生产环境API 和 路由
	API_URL = 'https://postrings.lotaoup.com/api'
	Vue.prototype.$BASE_PATH = 'https://pm.lotaoup.com'
}

// API_URL = 'https://pd.lotaoup.com/api'
// Vue.prototype.$BASE_PATH = 'https://pdm.lotaoup.com'


import store from '../store/index.js'
let platform = ''
// #ifdef H5
platform = 2
// #endif
// #ifndef H5
switch (uni.getSystemInfoSync().platform) {
	case 'android':
		platform = 1
		break;
	case 'ios':
		platform = 1
		break;
}
// #endif
const request = function(options) {
	const token = 'Bearer ' + uni.getStorageSync('token')
	//是否POST方法header讲JSON序列化
	let type = false
	//是否显示借口请求遮罩层
	let showLoading = options.showLoading === undefined ? false : options.showLoading
	//是否显示错误弹窗
	let showError = options.showError === undefined ? false : options.showError
	if (showLoading) {
		uni.showLoading({
			mask: true,
			title: '请求中...',
		})
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: API_URL + options.url,
			data: options.data === undefined ? options.params : options.data,
			method: options.method || 'GET',
			dataType: 'json',
			header: {
				'X-Requested-With': 'XMLHttpRequest',
				'lang': uni.getStorageSync('select') || 'tw',
				'accept': 'application/json',
				'content-type': type ? 'application/x-www-form-urlencoded' : 'application/json',
				'Authorization': token,
				'platform': platform
			},
			success: res => {
				resInfo.resTrue()
				showLoading && uni.hideLoading()
				if (res.statusCode !== 200 || res.data.code > 300) {
					if (res.statusCode === 401) {
						//退出登录
						store.commit('auth/LOGIN_OUT')
						//清空个人信息
						store.commit('auth/SET_USER', null)
						//清除个人相关本地缓存
						uni.removeStorageSync('token');
						
						uni.redirectTo({
							url: '/pages/login/login'
						})
					} else {
						if (!showError) {
							if (res.data.code != 402 && res.data.code != 433) {
								uni.showToast({
									title: res.data.message,
									icon: 'none',
									duration: 2000
								})
							}
						}
					}
					reject(res)
				} else {
					resolve(res.data)
				}
			},
			fail: res => {
				resInfo.resTrue()
				// uni.showToast({
				// 	title: '网络不给力，请稍后再试~',
				// 	icon: 'none',
				// 	duration: 2000
				// })
				reject(res)
			}
		})
	})
}
export default request
